/*******************************************************************************
 * @project: aohuaproject
 * @package: com.aohua.erp
 * @file: ExportBOMsIntoERPService.java
 * @author: fionn
 * @created: 2015年9月22日
 * @purpose:
 * 
 * @version: 1.0
 * 
 * 
 * Copyright 2015 HAND All rights reserved.
 ******************************************************************************/
package com.aohua.erp;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.agile.api.APIException;
import com.agile.api.ChangeConstants;
import com.agile.api.ICell;
import com.agile.api.IItem;
import com.agile.api.IRedlined;
import com.agile.api.IRow;
import com.agile.api.ITable;
import com.agile.api.ITwoWayIterator;
import com.agile.api.ItemConstants;
import com.hand.agile.utils.CellUtils;

/**
 * @author fionn
 *
 */
public class ExportBOMsIntoERPService {

    private static Logger log = Logger.getLogger(ExportBOMsIntoERPService.class);
    
    private boolean needExportBOM(IItem item) throws APIException {
        ITable bomTbl = item.getTable(ItemConstants.TABLE_BOM);
        if(!bomTbl.isEmpty()) return true;
        ITable redlineBomTbl = item.getTable(ItemConstants.TABLE_REDLINEBOM);
        return !redlineBomTbl.isEmpty();
    }
    
    public void extractBomPayload(IRow aiRow, String pid, List<ERPBomPayload> payloads, List<String> exportItems) throws APIException {
        IItem item = (IItem)aiRow.getReferent();
        System.out.println(item.getName() + " need export BOM?  -" + needExportBOM(item));
        if(!needExportBOM(item)) return;
        System.out.println(item.getName() + " exports BOMs into SAP.");
        // 是否委外加工
        ICell cell = item.getCell(ItemConstants.ATT_PAGE_TWO_LIST16);
        String wwjg = CellUtils.getCellStringValue(cell);
        
        // 物料属性
        cell = item.getCell(ItemConstants.ATT_PAGE_TWO_LIST12);
        String feature = CellUtils.getCellStringValue(cell);
        String fix = (feature != null && (feature.contains("外协") || feature.contains("外购"))) ? "G" : "M"; 
        if("G".equals(fix)) {
            fix = "Y".equals(wwjg) ? "W" : fix; // 委外加工
        }
        // 代码
        String parentCode = item.getName() + fix;
        exportItems.add(parentCode);
        
        // 父料分类
        cell = item.getCell(ItemConstants.ATT_TITLE_BLOCK_PART_TYPE);
        String category = CellUtils.getCellStringValue(cell);
        
        cell = aiRow.getCell(ChangeConstants.ATT_AFFECTED_ITEMS_NEW_REV);
        String revision = CellUtils.getCellStringValue(cell);
        
        Object evdate = aiRow.getValue(ChangeConstants.ATT_AFFECTED_ITEMS_EFFECTIVE_DATE);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String effectivityDate = evdate == null ? "" : sdf.format((Date) evdate);
        
        Map<String, RedlineInfo> redlineInfos = getItemRedlineInfos(item);
        int level = 1;
        IRow row = null;
        ERPBomPayload payload = null;
        ITable bomTbl = item.getTable(ItemConstants.TABLE_BOM);
        ITwoWayIterator bomit = bomTbl.getTableIterator();
        while(bomit.hasNext()) {
            row = (IRow) bomit.next();
            payload = getBomPayloadFromRow(row);
            // PID
            payload.setPid(pid);
            // Level
            payload.setLevel(level);
         // 父料代码
            payload.setParentCode(parentCode);
            // 父料分类
            payload.setParentCategory(category);
         // （1级父料）版本
            payload.setVersion(revision);
         // （1级父料）生效日期
            payload.setEffectivityDate(effectivityDate);
            // Redline
            updateRedlineInfo(payload, redlineInfos);
            
            payloads.add(payload);
        }
        System.out.println(pid + " has BOM count :" + payloads.size());
    }
    
    /**
     * @param payload
     * @param redlineInfos
     */
    private void updateRedlineInfo(ERPBomPayload payload, Map<String, RedlineInfo> redlineInfos) {
        if(redlineInfos.isEmpty()) return;
        String subCode = payload.getSubCode();
        RedlineInfo info = redlineInfos.get(subCode);
        if(info == null) return;
        payload.setRedLine(info.getRedline());
        payload.setNote(info.getRedlineNote());
    }

    private ERPBomPayload getBomPayloadFromRow(IRow row) throws APIException {
        ERPBomPayload payload = new ERPBomPayload();
        IItem subItem = (IItem)row.getReferent();
        
        // Qty
        ICell cell = row.getCell(ItemConstants.ATT_BOM_QTY);
        payload.setQty(CellUtils.getCellStringValue(cell));
        // 查找号
        cell = row.getCell(ItemConstants.ATT_BOM_FIND_NUM);
        payload.setFindNum(CellUtils.getCellStringValue(cell));
        // 替代料标记
        cell = row.getCell(new Integer(1636));
        String value = CellUtils.getCellStringValue(cell);
        payload.setSubflag("替".equals(value) ? "S" : "M");
        // (子料)是否委外加工
        cell = subItem.getCell(ItemConstants.ATT_PAGE_TWO_LIST16);
        value = CellUtils.getCellStringValue(cell);
        payload.setSubWgjg("是".equals(value) ? "Y" : "N");
        
        // (子料)物料属性
        cell = subItem.getCell(ItemConstants.ATT_PAGE_TWO_LIST12);
        value = CellUtils.getCellStringValue(cell);
        String fix = (value != null && (value.contains("外协") || value.contains("外购"))) ? "G" : "M"; 
        if("G".equals(fix)) {
            fix = "Y".equals(payload.getSubWgjg()) ? "W" : fix; // 委外加工
        }
        payload.setSubItemFeature(fix);
        
        // 子料代码
        payload.setSubCode(subItem.getName()+fix);
     // （子料）单位
        cell = subItem.getCell(ItemConstants.ATT_PAGE_TWO_LIST11);
        payload.setSubUnit(CellUtils.getCellStringValue(cell));
     // （子料）数量
        cell = subItem.getCell(ItemConstants.ATT_PAGE_TWO_TEXT12);
        payload.setSubCount(CellUtils.getCellStringValue(cell));
     // （子料）素材料号
        cell = subItem.getCell(ItemConstants.ATT_PAGE_TWO_LIST17);
        payload.setSubSCCode(CellUtils.getCellStringValue(cell));
     // (子料)毛坯料号
        cell = subItem.getCell(ItemConstants.ATT_PAGE_TWO_LIST18);
        payload.setSubMPCode(CellUtils.getCellStringValue(cell));
        return payload;
    }
    
    /**
     * @param item
     * @return
     * @throws APIException 
     */
    private Map<String, RedlineInfo> getItemRedlineInfos(IItem item){
        Map<String, RedlineInfo> rlinfos = new HashMap<String, RedlineInfo>();
        try {
            ITable table = item.getTable(ItemConstants.TABLE_REDLINEBOM);
            ITwoWayIterator redIt = table.getTableIterator();
            while(redIt.hasNext()) {
                RedlineInfo info = new RedlineInfo();
                IRow row = (IRow)redIt.next();
                IItem subitem = (IItem)row.getReferent();
             // 是否委外加工
                ICell cell = subitem.getCell(ItemConstants.ATT_PAGE_TWO_LIST16);
                String wwjg = CellUtils.getCellStringValue(cell);
                
                // 物料属性
                cell = subitem.getCell(ItemConstants.ATT_PAGE_TWO_LIST12);
                String feature = CellUtils.getCellStringValue(cell);
                String fix = (feature != null && (feature.contains("外协") || feature.contains("外购"))) ? "G" : "M"; 
                if("G".equals(fix)) {
                    fix = "Y".equals(wwjg) ? "W" : fix; // 委外加工
                }
                
                System.out.println("Redline BOM row : " + subitem + " with " + row.getValue(new Integer(6795)));
                rlinfos.put(subitem.getName()+fix, info);
                IRedlined redRow = (IRedlined) row;
                if(redRow.isRedlineModified()) {
                    // modified
                    info.setRedline("M");
                    cell = row.getCell(ItemConstants.ATT_BOM_QTY);
                    StringBuffer note = new StringBuffer();
                    if(((IRedlined)cell).isRedlineModified()) {
                        String oldv = (String)cell.getOldValue();
                        String newv = (String)cell.getValue();
                        note.append("用量: ").append(oldv).append(" => ").append(newv).append(";");
                    }
                    cell = row.getCell(ItemConstants.ATT_BOM_BOM_TEXT01);
                    if(((IRedlined)cell).isRedlineModified()) {
                        String oldv = (String)cell.getOldValue();
                        String newv = (String)cell.getValue();
                        note.append("替代料: ").append(oldv).append(" => ").append(newv).append(";");
                    }
                    info.setRedlineNote(note.toString());
                }else {
                    // add or remove
                    info.setRedline(Boolean.parseBoolean((String)row.getValue(new Integer(6795))) ? "A" : ""); 
                    cell  = row.getCell(ItemConstants.ATT_BOM_ITEM_NUMBER);
                    System.out.println(cell.getOldValue() + " -> " + cell.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return rlinfos;
    }
}
